package com.ts.proj.json;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import com.ts.base.controller.BaseController;
import com.ts.common.constant.InsUpdDelFlagConstant;
import com.ts.proj.entity.*;
import com.ts.proj.service.FileService;
import com.ts.proj.service.SystemColumnService;
import com.ts.proj.service.MarketService;
import com.ts.common.constant.ConsoleConstant;
import com.ts.proj.service.SystemFieldService;
import com.ts.util.PageData;
import com.ts.util.StringsUtil;
import com.ts.util.DateUtil;
import com.ts.util.EntityAttributeUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import java.util.*;
import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;
import com.ts.util.*;




import javax.servlet.http.HttpSession;
import com.ts.proj.entity.SystemUserEntity;

import com.ts.common.constant.ConsoleConstant;

//说明 字符串：Market，作为替换字符串 LOWERMarket

@RestController
public class MarketJson extends BaseController{

    @Autowired
    private MarketService marketService;
	@Autowired
    private SystemFieldService systemFieldService;
	
	  @Autowired
    private SystemColumnService systemColumnService;

    @Autowired
    private FileService fileService;

    @Value("${upload.location-pre}")
    private String locaionPre ;

    @Value("${upload.split}")
    private String split;

    /**
     * 显示list
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "/market-list/{page}/{size}/{id}")
    public Map<String,Object> marketList(@PathVariable("page") Integer page, @PathVariable("size") Integer size,@PathVariable("id") Integer id){
	
		HttpSession session = this.getRequest().getSession();
        SystemUserEntity user = JsonUtils.jsonToObject(session.getAttribute(ConsoleConstant.SESSIONUSER).toString(),SystemUserEntity.class);
	
        PageData pageData = this.getPageData();
        pageData.put("deleteFlag", "N");
        pageData.put("proId", id);
		
		//用户权限
        if(user.getPowerLevel().equals("0")){
            pageData.put("userId", user.getId());
        }
        pageData.put("belongTo", user.getBelongTo());
		
        long count = marketService.count(pageData);
        List<MarketEntity> markets = marketService.findAll(pageData,page-1,size);
        pageData.put("total",count);
        pageData.put("rows", markets);
        return pageData;
    }

    /**
     * 常量增删改
     * @return
     */
    @RequestMapping(value = "/market-ins-upd-del/{id}")
    public Object logCreateUpdate(@PathVariable("id") String id){
	
        MarketEntity market = marketService.findById(Integer.valueOf(id));
        PageData pageData = this.getPageData();

        List<String> strings = EntityAttributeUtil.entityAttribute(MarketEntity.class);
		 SystemUserEntity systemUserEntity = JsonUtils.jsonToObject(this.getRequest().getSession().getAttribute(ConsoleConstant.SESSIONUSER).toString(),SystemUserEntity.class);

        for(String attr :strings){
            //字段信息维护
            if(null!=pageData.get(attr)&&!"".equals(pageData.get(attr).toString())){
                //目前只能手动添加，这里添加所需要增加和修改的字段
                try {
                    Method[] methods = MarketEntity.class.getDeclaredMethods();
                    for(int i=0;i<methods.length;i++){
                        Method method = methods[i];
                        Class<?>[] returnType = method.getParameterTypes();
                        if(method.getName().equals("set"+StringsUtil.upperCase(attr))){
                            if (returnType[0].getName().equals("java.lang.Integer")){
                                method.invoke(market, Integer.valueOf(pageData.getString(attr)));
                            }
                            else{
                                System.out.println(attr);
                                method.invoke(market, pageData.getString(attr));
                            }
                        }
						if(method.getName().equals("setUserId")){
                            market.setUserId(systemUserEntity.getId());
                        }
                        if(method.getName().equals("setBelongTo")){
                            market.setBelongTo(systemUserEntity.getBelongTo());
                        }
						if(method.getName().equals("setPowerLevel")){
                            market.setPowerLevel(systemUserEntity.getPowerLevel());
                        }

                    }

                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }  catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
        //删除财务信息以及该信息下的文件（根据docType）
        if(null!=pageData.get("deleteFlag")&&!"".equals(pageData.get("deleteFlag").toString())){
            //1、根据doc_type可以查出所有相关联file（th_zt_meet_[meetid]）
            PageData pageData1 = new PageData();
            pageData1.put("deleteFlag", "N");
            pageData1.put("docType", "th_zt_market_"+market.getId());
            List<FileEntity> fileEntityList = fileService.findAll(pageData1);
            //遍历文件，删除
            for(FileEntity fileEntity : fileEntityList) {
                String path = locaionPre;
                path += fileEntity.getUuid() + split + fileEntity.getState()
                        + split + fileEntity.getFileName();
                fileEntity.setDeleteFlag("Y");
                fileService.save(fileEntity);
                File localFile = new File(path);
                localFile.delete();
            }
            market.setDeleteFlag(pageData.get("deleteFlag").toString());
        }
        marketService.save(market);
        return "success！";
    } 
	@RequestMapping("/market-download/{entity}")
    public void export(HttpServletResponse response,@PathVariable("entity") String entity){
        PageData param = new PageData();
        param.put("deleteFlag", InsUpdDelFlagConstant.DELETE_FLAG_N);
        List<MarketEntity> entitys = marketService.findAll(param);
		param.put("isExport", "Y");
        param.put("tableName", StringsUtil.upperCase(entity));
        List<SystemFieldEntity> all = systemFieldService.findAll(param);
        List<ExcelExportEntity> columnList = new ArrayList<ExcelExportEntity>();
        List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
        //get all columns
        for(SystemFieldEntity systemFieldEntity : all){
            ExcelExportEntity excelExportEntity = new ExcelExportEntity(systemFieldEntity.getFieldCn(), systemFieldEntity.getFieldEn());
			
			if(EntityUtil.getTypeByFieldName(MarketEntity.class,systemFieldEntity.getFieldEn()).equals("Integer")){
                excelExportEntity.setType(10);
            }else if(EntityUtil.getTypeByFieldName(MarketEntity.class,systemFieldEntity.getFieldEn()).equals("String")){
                if(null!=systemFieldEntity.getIsMerge()&&systemFieldEntity.getIsMerge().equals("Y")){
                    excelExportEntity.setMergeVertical(true);
                }
            }		
			
            columnList.add(excelExportEntity);
        }
        //get all data
        for(MarketEntity te: entitys){
            Map<String, Object> map = new HashMap<>();
            for(SystemFieldEntity systemFieldEntity : all){
                String fieldName = systemFieldEntity.getFieldEn();
                String getFunctionName = "get" + StringsUtil.upperCase(fieldName);
                try {
                    Method method = MarketEntity.class.getMethod(getFunctionName);
                    Object invoke = method.invoke(te);
                    map.put(fieldName, invoke);
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
            dataList.add(map);
        }
        
		PageData temp = new PageData();
        temp.put("deleteFlag", "N");
        temp.put("className", StringsUtil.upperCase(entity));
        List<SystemColumnEntity> columnEntities = systemColumnService.findAll(temp);
        ExportParams exportParams = null;
        if(1==columnEntities.size()){
            exportParams = new ExportParams(columnEntities.get(0).getExportTitle(), columnEntities.get(0).getExportSheet());
        }else{
            exportParams = new ExportParams("SystemColumnEntity数据表此数据不存在胡搜好请确认此条信息", "SHeet");
        }
		
		
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, columnList, dataList);
        try {
            response.setHeader("Content-Disposition","attachment;filename=" + new String((DateUtil.getID()+".xls").getBytes("UTF-8"), "iso8859-1"));
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            BufferedOutputStream bufferedOutPut = new BufferedOutputStream(response.getOutputStream());
            workbook.write(bufferedOutPut);
            bufferedOutPut.flush();
            bufferedOutPut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
      
    }	
}